package com.zmn.oms.zmn.normal.business.impl.work.financework;

import com.alibaba.fastjson.JSON;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.math.MathUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.consts.GlobalConsts;
import com.zmn.erp.common.newbiz.dio.CompensateAccountDIO;
import com.zmn.erp.common.newbiz.dio.OrderAccountDIO;
import com.zmn.erp.common.newbiz.dio.RefundOrderAccountDIO;
import com.zmn.erp.common.newbiz.dio.ReworkOrderAccountDIO;
import com.zmn.erp.common.newbiz.dro.account.auto.AutoAccountResultDRO;
import com.zmn.erp.dubbo.interfaces.newbiz.account.auto.AccountAutoRemoteService;
import com.zmn.erp.dubbo.utils.DubboConsts;
import com.zmn.manager.mq.interfaces.ZmnMQSender;
import com.zmn.oms.business.interfaces.conf.checkout.ConfCheckoutBService;
import com.zmn.oms.business.interfaces.discount.OrderDiscountBService;
import com.zmn.oms.business.interfaces.log.OrderLogBService;
import com.zmn.oms.business.interfaces.warranty.OrderWarrantyBService;
import com.zmn.oms.business.interfaces.work.erp.OrderAccountInfoListBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderPayConsts;
import com.zmn.oms.common.dto.OmsOperator;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.work.erp.CompensateOrderAccountInfoDTO;
import com.zmn.oms.model.dto.work.erp.NewOrderAccountInfoDTO;
import com.zmn.oms.model.dto.work.erp.RefundOrderAccountInfoDTO;
import com.zmn.oms.model.dto.work.erp.ReworkOrderAccountInfoDTO;
import com.zmn.oms.model.dto.work.modify.ZsSyncAccountDIO;
import com.zmn.oms.model.entity.account.OrderAccountResult;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.log.OrderLog;
import com.zmn.oms.model.entity.part.OrderPart;
import com.zmn.oms.model.entity.pay.OrderPay;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.account.OrderAccountResultService;
import com.zmn.oms.services.interfaces.comment.OrderCommentService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.discount.OrderDiscountService;
import com.zmn.oms.services.interfaces.factory.OrderFactoryService;
import com.zmn.oms.services.interfaces.fcorderpart.OrderFactoryPartService;
import com.zmn.oms.services.interfaces.invoice.OrderInvoiceService;
import com.zmn.oms.services.interfaces.master.OrderMasterService;
import com.zmn.oms.services.interfaces.member.OrderMemberService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.part.OrderPartService;
import com.zmn.oms.services.interfaces.pay.OrderPayService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.work.OrderWorkAmountService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.services.interfaces.work.financework.FinanceWorkService;
import com.zmn.oms.zmn.aop.OrderWorkLogUtils;
import com.zmn.oms.zmn.business.interfaces.work.orderpay.ZsOrderPayBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.financework.ZsNormalAccountWorkBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.financework.ZsNormalErpFinanceWorkBService;
import com.zmn.pay.common.constant.PayConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author sunlife
 * @date:2021/7/27 2:17 下午
 * description:
 */
@Service
@Slf4j
public class ZsNormalAccountWorkBServiceImpl implements ZsNormalAccountWorkBService {


    @Autowired
    protected OrderWorkService orderWorkService;

    @Autowired
    protected OrderDetailService orderDetailService;

    @Autowired
    protected OrderExtendService orderExtendService;

    @Autowired
    protected OrderMasterService orderMasterService;

    @Autowired
    protected FinanceWorkService financeWorkService;

    @Autowired
    protected OrderPartService orderPartService;

    @Autowired
    protected OrderDiscountService orderDiscountService;

    @Autowired
    protected OrderInvoiceService orderInvoiceService;

    @Autowired
    protected ZsOrderPayBService zsOrderPayBService;

    @Autowired
    protected OrderFactoryService orderFactoryService;

    @Autowired
    protected OrderDiscountBService orderDiscountBService;

    @Resource
    protected ZmnMQSender zmnMQSender;

    @Autowired
    protected OrderWarrantyBService orderWarrantyBService;

    @Autowired
    OrderWorkAmountService orderWorkAmountService;

    @Autowired
    OrderCommentService orderCommentService;

    @Autowired
    OrderServiceItemService orderServiceItemService;

    @Autowired
    OrderMemberService orderMemberService;

    @Autowired
    ConfCheckoutBService confCheckoutBService;

    @Autowired
    OrderFactoryPartService orderFactoryPartService;

    @Autowired
    OrderPayService orderPayService;

    @Autowired
    OrderAccountResultService orderAccountResultService;

    @Autowired
    ZsNormalErpFinanceWorkBService zsNormalErpFinanceWorkBService;

    @Autowired
    OrderAccountInfoListBService orderAccountInfoListBService;

    @Autowired
    OrderLogBService orderLogBService;

    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    AccountAutoRemoteService accountAutoRemoteService;

    @Override
    public void verifyOrderAmount(OrderWork orderWork) throws OmsBaseException {

        // 非新单不校验
        if (!Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)) {
            return;
        }

        // 保内单不校验
        if (Objects.equals(orderWork.getBizType(), com.zmn.consts.GlobalConsts.BIZ_TYPE_F)) {
            return;
        }

        List<OrderPay> orderPays = orderPayService.listOrderPayByOrderIdAndWorkId(orderWork.getOrderId(), orderWork.getWorkId())
                .stream()
                .filter(e -> !Objects.equals(e.getPayChannelId(), PayConsts.PAY_CHANNEL_PLATFORM_DISCOUNT)
                        && !Objects.equals(e.getDuplicate(), GlobalConsts.YES)
                )
                .collect(Collectors.toList());

        // 校验1，应收 = 已支付渠道代收 + 已支付平台预收 + 已支付定金 + 已支付师傅收款
        Integer factAmount = this.factAmount(orderWork);
        if (!Objects.equals(orderWork.getTotalAmount(), factAmount)) {
            int refundAmt = orderPays.stream()
                    .filter(e -> Objects.equals(e.getTradeType(), PayConsts.PAY_TRADE_TYPE_REFUND))
                    .mapToInt(e -> e.getAmount())
                    .sum();
            // 一口价原单退款（实际收款-退款）校验
            if (!Objects.equals(orderWork.getTotalAmount(), factAmount - refundAmt)) {
                throw new OmsBaseException("算账异常：已支付金额不等于应收金额");
            }
        }

        // 校验2，支付凭证和工单上记录款项校验（渠道代收例外）
        Integer paidPrepayAmt = 0;
        Integer paidDepositAmt = 0;
        Integer paidMasterAmt = 0;
        Integer warrantyAmt = 0;

        if (CollectionUtil.isNotNullOrEmpty(orderPays)) {
            paidPrepayAmt = orderPays.stream()
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_PREPAY))
                    .mapToInt(e -> e.getAmount()).sum();
            paidDepositAmt = orderPays.stream()
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_DEPOSIT)
                            || Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_PROGRESS))
                    .mapToInt(e -> e.getAmount()).sum();
            paidMasterAmt = orderPays.stream()
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_MASTER)
                            && Objects.equals(e.getTradeType(), PayConsts.PAY_TRADE_TYPE_INTIME)
                            && !Objects.equals(PayConsts.PAY_CHANNEL_PLATFORM_DEPOSIT,e.getPayChannelId())
                    ).mapToInt(e -> e.getAmount())
                    .sum();
            warrantyAmt = orderPays.stream()
                    .filter(e -> Objects.equals(e.getAmountType(), OrderPayConsts.ORDER_PAY_MASTER)
                            && Objects.equals( PayConsts.PAY_TRADE_TYPE_INTIME,e.getTradeType())
                            && Objects.equals(PayConsts.PAY_CHANNEL_PLATFORM_DEPOSIT,e.getPayChannelId())
                    ).mapToInt(e -> e.getAmount())
                    .sum();
        }
        Integer prepayAmt = Optional.ofNullable(orderWork.getPrepayAmount()).orElse(0);
        Integer depositAmt = Optional.ofNullable(orderWork.getDepositAmount()).orElse(0);
        Integer masterAmt = Optional.ofNullable(orderWork.getMasterAmount()).orElse(0);

        if (!Objects.equals(prepayAmt, (paidPrepayAmt + warrantyAmt)) || !Objects.equals(depositAmt, paidDepositAmt) || !Objects
                .equals(masterAmt, paidMasterAmt)) {
            throw new OmsBaseException("算账异常：已支付凭证不等于工单收款项");
        }

        // 校验3，订单金额 = 应收 + 优惠 校验
        Integer discountAmount = Optional.ofNullable(orderWork.getDiscountAmount()).orElse(0);
        Integer calcTotalAmt = MathUtil.sub(orderWork.getOriginalAmount(), discountAmount);
        calcTotalAmt += Optional.ofNullable(orderWork.getDiscountPrepayAmount()).orElse(0);
        calcTotalAmt -= Optional.ofNullable(orderWork.getPayDiscountAmount()).orElse(0);
        if (!Objects.equals(calcTotalAmt, orderWork.getTotalAmount())) {
            throw new OmsBaseException("算账异常：原价不等于应收+优惠");
        }

        // 校验4，订单金额 = 服务项表价格之和
        Integer serviceItemTotalPrice = 0;
        List<OrderServiceItem> orderServiceItems = orderServiceItemService.listByOrderId(orderWork.getOrderId());
        if (CollectionUtil.isNotNullOrEmpty(orderServiceItems)) {
            serviceItemTotalPrice = orderServiceItems.stream().filter(e -> e.getTotalPrice() != null)
                    .mapToInt(e -> e.getTotalPrice()).sum();
        }
        if (!Objects.equals(serviceItemTotalPrice, orderWork.getOriginalAmount())) {
            throw new OmsBaseException("算账异常：原价不等于服务项金额之和");
        }

        // 校验5，工单上冗余的优惠总价 = 优惠表各优惠之和
        Integer orderDiscountsAmt = 0;
        List<OrderDiscount> orderDiscounts = orderDiscountService.listByOrderId(orderWork.getOrderId());
        if (CollectionUtil.isNotNullOrEmpty(orderDiscounts)) {
            orderDiscountsAmt = orderDiscounts.stream().filter(e -> e.getAmount() != null).mapToInt(e -> e.getAmount())
                    .sum();
        }
        if (!Objects.equals(orderDiscountsAmt, discountAmount)) {
            throw new OmsBaseException("算账异常：优惠金额异常");
        }

        // 校验6，工单上冗余的配件总价 = 内 + 外 + 运
        Integer partTotalAmt = Optional.ofNullable(orderWork.getPartAmount()).orElse(0);
        Integer inSourAmt = Optional.ofNullable(orderWork.getInSourcingAmount()).orElse(0);
        Integer outSourAmt = Optional.ofNullable(orderWork.getOutSourcingAmount()).orElse(0);
        Integer deliverAmt = Optional.ofNullable(orderWork.getDeliverAmount()).orElse(0);
        if (partTotalAmt != inSourAmt + outSourAmt + deliverAmt) {
            throw new OmsBaseException("算账异常：配件金额异常");
        }

        // 校验7，工单上冗余的 内 + 外 + 运 总额 = 配件表金额
        Integer orderInSourAmt = 0;
        Integer orderOutSourAmt = 0;
        Integer orderDeliverAmt = 0;
        List<OrderPart> orderParts = orderPartService.listByOrderId(orderWork.getOrderId());
        if (CollectionUtil.isNotNullOrEmpty(orderParts)) {
            orderInSourAmt = orderParts.stream()
                    .filter(e -> Objects.equals(e.getPartType(), OrderConsts.PART_TYPE_SOURCING_IN)
                            && e.getPrice() != null && e.getNumber() != null)
                    .mapToInt(e -> com.zmn.oms.common.utils.MathUtil.amountMultiplyNumber(e.getPrice(), e.getNumber()))
                    .sum();
            orderOutSourAmt = orderParts.stream()
                    .filter(e -> Objects.equals(e.getPartType(), OrderConsts.PART_TYPE_SOURCING_OUT)
                            && e.getPrice() != null && e.getNumber() != null)
                    .mapToInt(e -> com.zmn.oms.common.utils.MathUtil.amountMultiplyNumber(e.getPrice(), e.getNumber()))
                    .sum();
            orderDeliverAmt = orderParts.stream()
                    .filter(e -> Objects.equals(e.getPartType(), OrderConsts.PART_TYPE_DELIVER) && e.getPrice() != null
                            && e.getNumber() != null).mapToInt(e -> com.zmn.oms.common.utils.MathUtil.amountMultiplyNumber(
                            e.getPrice(), e.getNumber())).sum();
        }
        if (!Objects.equals(inSourAmt, orderInSourAmt) || !Objects.equals(outSourAmt, orderOutSourAmt) || !Objects
                .equals(deliverAmt, orderDeliverAmt)) {
            throw new OmsBaseException("算账异常：配件金额异常2");
        }

    }


    /**
     * 获取实付金额
     *
     * @param orderWork
     * @return
     */
    private Integer factAmount(OrderWork orderWork) {
        Integer factAmount = 0;
        if (Objects.equals(orderWork.getChannelPrepayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil
                .isNullOrZero(orderWork.getChannelPrepayAmount())) {
            factAmount = factAmount + orderWork.getChannelPrepayAmount().intValue();
        }
        if (Objects.equals(orderWork.getPrepayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil
                .isNullOrZero(orderWork.getPrepayAmount())) {
            factAmount = factAmount + orderWork.getPrepayAmount().intValue();
        }
        if (Objects.equals(orderWork.getDepositStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil
                .isNullOrZero(orderWork.getDepositAmount())) {
            factAmount = factAmount + orderWork.getDepositAmount().intValue();
        }
        if (Objects.equals(orderWork.getMasterPayStatus(), PayConsts.PAY_STATUS_DONE) && !NumberUtil
                .isNullOrZero(orderWork.getMasterAmount())) {
            factAmount = factAmount + orderWork.getMasterAmount().intValue();
        }
        if (NumberUtil.isNotNullOrZero(orderWork.getDiscountPrepayAmount())) {
            factAmount = factAmount + orderWork.getDiscountPrepayAmount().intValue();
        }
        if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REFUND) && !NumberUtil.isNullOrZero(orderWork.getRefundAmount())) {
            factAmount = MathUtil.sub(factAmount, orderWork.getRefundAmount());
        }
        return factAmount;
    }


    @Override
    public void account(OrderWork orderWork, OmsOperator operator) throws OmsBaseException {
        // 请求算账
        ResponseDTO<AutoAccountResultDRO> responseDTO = null;
        switch (orderWork.getType()) {
            case OrderConsts.ORDER_TYPE_NEW:
                responseDTO = newOrderAccount(orderWork, operator);
                break;
            case OrderConsts.ORDER_TYPE_REWORK:
                responseDTO = reworkOrderAccount(orderWork, operator);
                break;
            case OrderConsts.ORDER_TYPE_REFUND:
                responseDTO = refundOrderAccount(orderWork, operator);
                break;
            case OrderConsts.ORDER_TYPE_COMPENSATE:
                responseDTO = compensateOrderAccount(orderWork, operator);
                break;
            default:
                responseDTO = ResponseDTO.fail("错误的工单类型");
        }

        // 算账结果处理
        if (!responseDTO.isSuccess()) {
            addAccountFailLog(orderWork, 2, responseDTO.getMessage());
            throw new OmsBaseException(String.format("算账错误：%s", responseDTO.getMessage()));
        }

        try {
            ZsSyncAccountDIO accountDIO;
            AutoAccountResultDRO resultDRO = responseDTO.getData();
            if (Objects.isNull(resultDRO)) {
                OrderAccountResult orderAccountResult = orderAccountResultService.findByKey(orderWork.getWorkId());
                if (Objects.isNull(orderAccountResult)) {
                    throw new Exception("算账结果数据为空");
                }

                accountDIO = BeanMapper.map(orderAccountResult, ZsSyncAccountDIO.class);
                accountDIO.setLogContent(orderAccountResult.getAccountLog());
            } else {
                accountDIO = BeanMapper.map(resultDRO, ZsSyncAccountDIO.class);
                accountDIO.setLogContent(resultDRO.getAccountLog());
            }

            accountDIO.setOrderId(orderWork.getOrderId());
            accountDIO.setWorkId(orderWork.getWorkId());
            zsNormalErpFinanceWorkBService.syncAccount(accountDIO);
            orderAccountResultService.deleteByKey(orderWork.getWorkId());
        } catch (Exception e) {
            addAccountFailLog(orderWork, 1, e.getMessage());
            log.error(String.format("算账异常：%s", orderWork.getWorkId()), e);
            throw new OmsBaseException(String.format("算账错误：%s", e.getMessage()));
        }
    }


    /**
     * 新单算账
     *
     * @param orderWork
     * @return
     */
    private ResponseDTO<AutoAccountResultDRO> newOrderAccount(OrderWork orderWork, OmsOperator operator) throws OmsBaseException {
        NewOrderAccountInfoDTO newOrderAccountInfoDTO = orderAccountInfoListBService.getNewOrderAccountInfo(orderWork);
        OrderAccountDIO accountDIO = BeanMapper.map(newOrderAccountInfoDTO, OrderAccountDIO.class);
        accountDIO.setTryCalculate(false);
        accountDIO.setOperatorName(operator.getOperator());
        accountDIO.setOperatorType(operator.getOperatorType());
        accountDIO.setOperatorId(operator.getOperatorId().intValue());
        accountDIO.setVasPreSellAmount(orderWork.getDiscountPrepayAmount());
        log.info("[{}]订单算账入参：{}", orderWork.getWorkId(), JSON.toJSONString(accountDIO));
        ResponseDTO<AutoAccountResultDRO> resultDROResponseDTO = accountAutoRemoteService.generalOrderAccount(accountDIO);
        log.info("[{}]订单算账出参：{}", orderWork.getWorkId(), JSON.toJSONString(resultDROResponseDTO));
        return resultDROResponseDTO;
    }

    /**
     * 退款单算账
     *
     * @param orderWork
     * @return
     */
    private ResponseDTO<AutoAccountResultDRO> refundOrderAccount(OrderWork orderWork, OmsOperator operator) {
        RefundOrderAccountInfoDTO refundOrderAccountInfo = orderAccountInfoListBService.getRefundOrderAccountInfo(orderWork);
        RefundOrderAccountDIO accountDIO = BeanMapper.map(refundOrderAccountInfo, RefundOrderAccountDIO.class);
        accountDIO.setOrderTime(refundOrderAccountInfo.getReceiveTime());
        accountDIO.setTryCalculate(false);
        accountDIO.setOperatorName(com.zmn.common.constant.GlobalConsts.getOperatorTypeName(com.zmn.common.constant.GlobalConsts.OPERATE_USER_TYPE_SYSTEM));
        accountDIO.setOperatorName(operator.getOperator());
        accountDIO.setOperatorType(operator.getOperatorType());
        accountDIO.setOperatorId(operator.getOperatorId().intValue());
        log.info("[{}]订单算账入参：{}", orderWork.getWorkId(), JSON.toJSONString(accountDIO));
        ResponseDTO<AutoAccountResultDRO> resultDROResponseDTO = accountAutoRemoteService.refundOrderAccount(accountDIO);
        log.info("[{}]订单算账出参：{}", orderWork.getWorkId(), JSON.toJSONString(resultDROResponseDTO));
        return resultDROResponseDTO;

    }

    /**
     * 赔偿单算账
     *
     * @param orderWork
     * @return
     */
    private ResponseDTO<AutoAccountResultDRO> compensateOrderAccount(OrderWork orderWork, OmsOperator operator) {
        CompensateOrderAccountInfoDTO compensateOrderAccountInfoDTO = orderAccountInfoListBService.getCompensateOrderAccountInfo(orderWork);
        CompensateAccountDIO accountDIO = BeanMapper.map(compensateOrderAccountInfoDTO, CompensateAccountDIO.class);
        accountDIO.setOperatorName(com.zmn.common.constant.GlobalConsts.getOperatorTypeName(com.zmn.common.constant.GlobalConsts.OPERATE_USER_TYPE_SYSTEM));
        accountDIO.setOperatorName(operator.getOperator());
        accountDIO.setOperatorType(operator.getOperatorType());
        accountDIO.setOperatorId(operator.getOperatorId().intValue());
        ResponseDTO<AutoAccountResultDRO> resultDROResponseDTO = accountAutoRemoteService.compensateOrderAccount(accountDIO);
        log.info("[{}]订单算账出参：{}", orderWork.getWorkId(), JSON.toJSONString(resultDROResponseDTO));
        return resultDROResponseDTO;

    }

    /**
     * 返修单算账
     *
     * @param orderWork
     * @return
     */
    private ResponseDTO<AutoAccountResultDRO> reworkOrderAccount(OrderWork orderWork, OmsOperator operator) throws OmsBaseException {
        ReworkOrderAccountInfoDTO reworkOrderAccountInfo = orderAccountInfoListBService.getReworkOrderAccountInfo(orderWork);
        ReworkOrderAccountDIO accountDIO = BeanMapper.map(reworkOrderAccountInfo, ReworkOrderAccountDIO.class);
        accountDIO.setOrderTime(reworkOrderAccountInfo.getReceiveTime());
        accountDIO.setTryCalculate(false);
        accountDIO.setOperatorName(operator.getOperator());
        accountDIO.setOperatorType(operator.getOperatorType());
        accountDIO.setOperatorId(operator.getOperatorId().intValue());
        log.info("[{}]订单算账入参：{}", orderWork.getWorkId(), JSON.toJSONString(accountDIO));
        ResponseDTO<AutoAccountResultDRO> resultDROResponseDTO = accountAutoRemoteService.reworkOrderAccount(accountDIO);
        log.info("[{}]订单算账出参：{}", orderWork.getWorkId(), JSON.toJSONString(resultDROResponseDTO));
        return resultDROResponseDTO;

    }

    public void accountBySys(OrderWork orderWork) {

        OmsOperator omsOperator = new OmsOperator();

        omsOperator.setOperator(com.zmn.common.constant.GlobalConsts.getOperatorTypeName(com.zmn.common.constant.GlobalConsts.OPERATE_USER_TYPE_SYSTEM));
        omsOperator.setOperatorType(com.zmn.common.constant.GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        omsOperator.setOperatorId((long) com.zmn.common.constant.GlobalConsts.OPERATE_USER_TYPE_SYSTEM);

        try {
            this.account(orderWork, omsOperator);
        } catch (OmsBaseException e) {
            log.error(String.format("[%s]自动算账失败", orderWork.getWorkId()), e);
        }
    }

    private void addAccountFailLog(OrderWork orderWork, Integer failModule, String failReason) {
        OmsOperator operator = new OmsOperator();
        operator.setOperatorType(GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        operator.setOperator("系统");
        operator.setOperatorId((long) GlobalConsts.OPERATE_USER_TYPE_SYSTEM);
        operator.setOrderId(orderWork.getOrderId());
        operator.setWorkId(orderWork.getWorkId());

        OrderLog orderLog = new OrderLog();

        // 算账失败原因
        StringBuilder sb = new StringBuilder();
        sb.append("-算账结果：失败；\n");
        sb.append("-失败缘由：\n");
        if (Objects.equals(failModule, 1)) {
            sb.append("- - 工单类型缘由：").append(failReason).append(";");
        } else if (Objects.equals(failModule, 2)) {
            sb.append("- - ERP类型缘由：").append(failReason).append(";");
        }

        orderLog.setContent(sb.toString());

        orderLog.setType(OrderLogConsts.ORDER_LOG_TYPE_ACCOUNT);
        orderLog.setTypeName(OrderLogConsts.getOrderLogTypeName(OrderLogConsts.ORDER_LOG_TYPE_ACCOUNT));
        OrderWorkLogUtils.processOrderLogOperater(orderLog, operator);
        OrderWorkLogUtils.processOrderLogStatus(orderLog, orderWork, operator);

        orderLog.setCreateTime(DateUtil.getNow());
        orderLogBService.save(orderLog);
    }
}
